package com.leigang.boot.redis.springbootredis.controller;

import com.leigang.boot.redis.springbootredis.entity.User;
import com.leigang.boot.redis.springbootredis.service.RedisService;
import com.leigang.boot.redis.springbootredis.utils.ResponseUtils;
import com.leigang.boot.redis.springbootredis.utils.SnowUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
public class RedisController {
    private final RedisService redisService;

    public RedisController(RedisService redisService) {
        this.redisService = redisService;
    }

    @GetMapping("/redis/getUser")
    public Map<String, Object> getUser(){
        List<User> userList = (List<User>)redisService.getObj("user");
        return ResponseUtils.success(userList);
    };

    @PostMapping("/redis/addUser")
    public Map<String, Object> addUser(@RequestBody User userVo){
        List<User> userList = (List<User>)redisService.getObj("user");
        if(userList==null){
            userList = new ArrayList<>();
        }
        User user1 = new User();
        user1.setId(SnowUtils.getId());
        user1.setName(userVo.getName());
        user1.setAge(userVo.getAge());
        user1.setHabbit(userVo.getHabbit());
        userList.add(user1);
        redisService.setObjs("user",userList);
        return ResponseUtils.success(user1);
    }
}
